<template>
  <div>
    {{ Man }}
  </div>
  <hr>
  <div>
    {{ Man2 }}
  </div>
  <hr>
  <div>
    {{ Man3 }}
  </div>
  <hr>
  <div>
    {{ obj }}
  </div>
  <hr>
  <div ref="dom">我是DOM</div>
  <button @click="change">修改</button>
</template>

<script setup lang="ts">
  import {ref, isRef, shallowRef, triggerRef, customRef} from "vue"
  
  // ref, isRef, shallowRef
  // ref 深层次 shallowRef 浅层次的响应

  const dom = ref<HTMLDivElement>()

  

  type M = {
    name: string
  }

  const Man = ref<M>({name: "小满"})
  const Man2 = {name: "小满"}
  const Man3 = shallowRef({name: "小满2"})

  const change = () => {
    console.log(isRef(Man))
    console.log(isRef(Man2))
    console.log(isRef(Man3))
    // Man.value.name = "大满"     // ref更新之后  也会引起shallowRef更新，底层调用triggerRef；如果这句不写，则shallowRef不会更新
    
    Man3.value.name = "大满2"
    triggerRef(Man3)               // 会引起shallowRef更新

    // shallowRef更新浅层
    // Man3.value = {
    //   name: "大满2"
    // }

    console.log(Man)
    console.log(Man3)

    obj.value = "customRef 修改啦"

    console.log(dom?.value?.innerText)
  }

  function MyRef<T>(value: T) {
    let timer:any
    return customRef((track:any, trigger:any) => {
      return {
        get () {
          // 收集依赖
          track()
          return value
        },
        set (newVal:any) {
          clearTimeout(timer)
          timer = setTimeout(() => {
            console.log("触发啦")
            value = newVal
            trigger()
          }, 500)
        }
      }
    })
  }
  
  const obj = MyRef<string>('小满')
</script>

<style scoped>

</style>